<script setup lang='ts'>
import type { FieldValues, PlusColumn } from 'plus-pro-components'

import { useAccountInfo, useAddAccount, useEditAccount, useGetRoleList } from '@fl/api/mall-api'
import { SubmitBtn } from '@fl/components'
import { cloneDeep } from 'lodash-es'

const { meta: { isAdmin } } = useRoute()
const id = defineModel<string>('id', { required: true })
const visible = defineModel<boolean>('visible', { required: true })

const form = ref()
const title = computed(() => {
    return id.value ? '编辑账户' : '新增账户'
})

const { isPending, mutate } = useAddAccount(isAdmin)
const { mutate: editAccountMutate } = useEditAccount(isAdmin)

const { data: roleList, isLoading: roleListLoading } = useGetRoleList(isAdmin)
const { data: accountInfo, isLoading: accountInfoLoading } = useAccountInfo(id, isAdmin)
const isLoading = computed(() => roleListLoading.value || accountInfoLoading.value)

const propertyOptions = computed(() => (roleList.value ?? []).map(x => ({ label: x.roleName, value: x.roleId })))

const initialState = {
    accountId: '',
    accountName: '',
    mobile: '',
    roleIds: [],
}
const state = ref<FieldValues>(cloneDeep(initialState))

watchEffect(() => {
    if (id.value) {
        if (accountInfo.value) {
            state.value = {
                accountId: accountInfo.value?.accountId,
                accountName: accountInfo.value?.accountName,
                mobile: accountInfo.value?.mobile,
                roleIds: accountInfo.value?.roleIds,
            }
        }
    }
})

const disabledFieldProps = computed(() => {
    return {
        disabled: !!id.value,
        maxlength: 11,
    }
})

const columns: PlusColumn[] = [
    {
        fieldProps: disabledFieldProps,
        label: '账户名',
        prop: 'accountName',
        width: 120,
    },
    {
        fieldProps: disabledFieldProps,
        label: '手机号',
        prop: 'mobile',
        width: 120,
    },
    {
        fieldProps: {
            multiple: true,
        },
        label: '角色',
        options: propertyOptions,
        prop: 'roleIds',
        valueType: 'select',
        width: 120,
    },
]

const rules = {
    accountName: [
        {
            message: '请填写账户名',
            required: true,
        },
    ],
    mobile: [
        {
            message: '请填写手机号',
            required: true,
        },
        { message: '手机号码格式不正确', pattern: /^1[3-9]\d{9}$/, trigger: 'blur' },
    ],
    roleIds: [
        {
            message: '请选择角色权限',
            required: true,
        },
    ],
}

async function confirm() {
    const valid = await form.value.formInstance.validate()
    if (valid) {
        const params = {
            ...state.value,
            accountId: id.value,
        }

        const fn = id.value ? editAccountMutate : mutate

        fn(params, {
            onSuccess: () => {
                ElMessage.success('操作成功')
                cancel()
            },
        })
    }
}

function cancel() {
    visible.value = false
}

function reset() {
    id.value = ''
    form.value.formInstance.resetFields()
}
</script>

<template>
    <PlusDialog v-model="visible"
                :title="title"
                width="800"
                close-on-press-escape
                @cancel="cancel"
                @closed="reset"
    >
        <ElSkeleton v-if="isLoading"
                    animated
        />

        <PlusForm v-else
                  ref="form"
                  v-model="state"
                  :columns="columns"
                  :label-width="100"
                  :rules="rules"
                  :has-footer="false"
        />

        <template #footer>
            <div class="mx-auto">
                <el-button @click="cancel">
                    取消
                </el-button>

                <SubmitBtn type="primary"
                           :loading="isPending"
                           @click="confirm"
                >
                    提交
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>
</template>
